package xin.de.weiauth.controller;

import lombok.extern.slf4j.Slf4j;
import me.chanjar.weixin.common.api.WxConsts;
import me.chanjar.weixin.common.exception.WxErrorException;
import me.chanjar.weixin.mp.api.WxMpService;
import me.chanjar.weixin.mp.bean.result.WxMpOAuth2AccessToken;
import me.chanjar.weixin.mp.bean.result.WxMpUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import xin.de.weiauth.config.ProjectUrlConfig;
import xin.de.weiauth.util.JsonUtil;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@Controller
@RequestMapping("/wx")
@Slf4j
public class WxAuthContrller {
    @Autowired
    private WxMpService wxMpService;
    @Autowired
    private ProjectUrlConfig projectUrlConfig;

    @GetMapping("/authorize")
    public String authorize(@RequestParam(name = "returnUrl",defaultValue = "") String returnUrl){
        //调用方法
        String url=projectUrlConfig.getWechatMpAuthorize()+"/wx/userInfo";
        log.info("return={}",returnUrl);
        /*会生成一个全新的链接,可以调用自己指定的方法,将code和state传过去,state是最后一个参数*/   //此处使用了user_info
        String redirectUrl = wxMpService.oauth2buildAuthorizationUrl(url, WxConsts.OAUTH2_SCOPE_USER_INFO, returnUrl);
        log.info(redirectUrl);
        return "redirect:"+redirectUrl;
    }
    @GetMapping("/userInfo")
    public String userInfo(@RequestParam("code") String code,
                                 @RequestParam("state") String returnUrl,
                                 HttpServletRequest request,
                                 Map<String,Object> map) throws WxErrorException {
        WxMpOAuth2AccessToken wxMpOAuth2AccessToken=new WxMpOAuth2AccessToken();

            wxMpOAuth2AccessToken = wxMpService.oauth2getAccessToken(code);
            log.info("调用一次");
            log.info("returnUrl={}",returnUrl);
        WxMpUser wxMpUser=new WxMpUser();
        try {
            wxMpUser = wxMpService.oauth2getUserInfo(wxMpOAuth2AccessToken, null);
        }
        catch (Exception e){

        }
        String result=wxMpUser.getOpenId()+","+wxMpUser.getHeadImgUrl()+","+wxMpOAuth2AccessToken.getAccessToken();
        return "redirect:"+returnUrl+"?result="+result;
    }
}
